package com.platform.common.utils;


import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * servlet request 取数据公共类
 *
 * @author LiangMingHui
 *
 */
public class RequestUtil {

	/**
	 * 从HttpServletRequest获取key的数据，不存在返回""
	 *
	 * @param request
	 * @param key
	 * @return
	 */
	public static String getRequestParameter(HttpServletRequest request, String key) {
		if (request == null || key == null || "".equals(key)) {
			return "";
		}
		String value = request.getParameter(key);
		if (value == null || "".equals(value)) {
			return "";
		} else {
			return value.trim();
		}
	}

	/**
	 * 从HttpServletRequest获取key的数据UTF-8格式，不存在返回""
	 *
	 * @param request
	 * @param key
	 * @return
	 */
	public static String getUTF8RequestParameter(HttpServletRequest request, String key) {
		if (request == null || key == null || "".equals(key)) {
			return "";
		}
		String value;
		try {
			value = URLDecoder.decode(request.getParameter(key), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			value = "";
		}
		if (value == null || "".equals(value)) {
			return "";
		} else {
			return value.trim();
		}
	}

	/**
	 * 从HttpServletRequest获取key的数据，不存在返回""
	 *
	 * @param request
	 * @param key
	 * @return
	 */
	public static Object getRequestAttribute(HttpServletRequest request, String key) {
		if (request == null || key == null || "".equals(key)) {
			return "";
		}
		Object value = request.getAttribute(key);
		if (value == null || "".equals(value)) {
			return "";
		} else {
			return value;
		}
	}

	/**
	 * 从HttpServletRequest获取key的数据，不存在返回返默认字串
	 *
	 * @param request
	 * @param key
	 * @param defaultStr
	 *            默认字符串
	 * @return
	 */
	public static String getRequestParameter(HttpServletRequest request, String key, String defaultStr) {
		if (request == null || key == null || "".equals(key)) {
			return defaultStr;
		}
		String value = request.getParameter(key);
		if (value == null || "".equals(value)) {
			return defaultStr;
		} else {
			return value.trim();
		}
	}

	/**
	 * 从HttpServletRequest获取key的数据，不存在返回""
	 *
	 * @param request
	 * @param key
	 * @return
	 */
	public static Object getRequestAttribute(HttpServletRequest request, String key, Object defaultObj) {
		if (request == null || key == null || "".equals(key)) {
			return defaultObj;
		}
		Object value = request.getAttribute(key);
		if (value == null || "".equals(value)) {
			return defaultObj;
		} else {
			return value;
		}
	}

	/**
	 * 获取ip
	 *
	 * @param request
	 * @return
	 */
	public static String getRemoteHost(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
	}

	/**
	 * 获取用户真实IP地址，不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址,
	 * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值
	 *
	 * @return ip
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个ip值，第一个ip才是真实ip
			if (ip.indexOf(",") != -1) {
				ip = ip.split(",")[0];
			}
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 获取布尔值
	 *
	 * @param request
	 * @param paramName
	 *            参数名
	 * @return
	 */
	public static boolean getBoolean(HttpServletRequest request, String paramName) {
		String paramValue = request.getParameter(paramName);
		if (StringUtils.isNotBlank(paramValue)) {
			if ("on".equalsIgnoreCase(paramValue)) {
				return true;
			}
			if ("ok".equalsIgnoreCase(paramValue)) {
				return true;
			}
			if ("true".equalsIgnoreCase(paramValue)) {
				return true;
			}
			if ("1".equals(paramValue)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取Double类型的值，默认为0D
	 *
	 * @param request
	 * @param paramName
	 * @return
	 */
	public static double getDouble(HttpServletRequest request, String paramName) {
		return getDouble(request, paramName, 0.0D);
	}

	/**
	 * 获取Double类型的值
	 *
	 * @param request
	 * @param paramName
	 *            参数名
	 * @param defaultValue
	 *            默认值
	 * @return
	 */
	public static double getDouble(HttpServletRequest request, String paramName, double defaultValue) {
		String paramValue = request.getParameter(paramName);
		return StringUtils.isNotBlank(paramValue) ? Double.parseDouble(paramValue) : defaultValue;
	}

	/**
	 * 获取int类型的值，默认为0
	 *
	 * @param request
	 * @param paramName
	 *            参数名
	 * @return
	 */
	public static int getInt(HttpServletRequest request, String paramName) {
		return getInt(request, paramName, 0);
	}

	/**
	 * 获取int类型的值
	 *
	 * @param request
	 * @param paramName
	 *            参数名
	 * @param defaultValue
	 *            默认值
	 * @return
	 */
	public static int getInt(HttpServletRequest request, String paramName, int defaultValue) {
		String paramValue = request.getParameter(paramName);
		return StringUtils.isNotBlank(paramValue) ? Integer.parseInt(paramValue) : defaultValue;
	}

	/**
	 * 获取String类型的值，默认为空
	 *
	 * @param request
	 * @param paramName
	 * @return
	 */
	public static String getString(HttpServletRequest request, String paramName) {
		String paramValue = getParameter(request, paramName);
		return StringUtils.isNotBlank(paramValue) ? paramValue : null;
	}

	/**
	 * 获取String类型的值
	 *
	 * @param request
	 * @param paramName
	 *            参数名
	 * @param defaultValue
	 *            默认值
	 * @return
	 */
	public static String getString(HttpServletRequest request, String paramName, String defaultValue) {
		String paramValue = getParameter(request, paramName);
		return StringUtils.isNotBlank(paramValue) ? paramValue : defaultValue;
	}

	/**
	 * 获取参数值，如果多个参数，以逗号隔开
	 *
	 * @param request
	 * @param name
	 * @return
	 */
	public static String getParameter(HttpServletRequest request, String name) {
		String value = request.getParameter(name);
		if (StringUtils.isEmpty(value)) {
			String[] values = request.getParameterValues(name);
			if (values != null && values.length > 0) {
				StringBuffer sb = new StringBuffer();
				for (int i = 0; i < values.length; i++) {
					sb = (i == values.length - 1) ? sb.append(values[i]) : sb.append(values[i]).append(",");
				}
				if (StringUtils.isNotEmpty(sb.toString())) {
					value = sb.toString();
				}
			}
		}
		return value;
	}

	/**
	 * 获取参数映射
	 *
	 * @param request
	 * @return
	 */
	public static Map<String, Object> getRequestParams(HttpServletRequest request) {
		Map<String, String[]> requestParams = request.getParameterMap();
		Map<String, Object> params = new HashMap<String, Object>();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			params.put(name, valueStr.trim());
		}
		return params;
	}

	/**
	 * 拆分查询参数，存入Map中
	 *
	 * @param queryStr
	 * @return
	 */
	public static Map<String, Object> getQueryParams(String queryStr) {
		Map<String, Object> queryMap = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(queryStr)) {
			String[] strAry = queryStr.split("&");
			for (int i = 0; i < strAry.length; i++) {
				String[] values = strAry[i].split("=");
				if (values.length > 1) {
					queryMap.put(values[0], values[1]);
				}
			}
		}
		return queryMap;
	}

	/**
	 * 返回指定表达式的字符串
	 *
	 * @param request
	 * @param name
	 * @param regex
	 *            表达式
	 * @return
	 */
	public static String getParameterValueByRegex(HttpServletRequest request, String name, String regex) {
		StringBuilder sb = new StringBuilder();
		String[] values = request.getParameterValues(name);
		if (values != null && values.length > 0) {
			for (int i = 0; i < values.length; i++) {
				sb = (i == values.length - 1) ? sb.append(values[i]) : sb.append(values[i]).append(regex);
			}
		}
		return sb.toString();
	}
}
